<template>
  <div class="second" style="height： 100vh;">
    <div v-if="ruleForm" class="content-box">
      <div class="teaching-box">
        <el-form
          ref="ruleForm"
          :rules="rules"
          class="teaching-form"
          label-width="140px"
          :model="ruleForm"
        >
          <!--  v-if="options.teachingTarget" -->
          <el-form-item v-if="options.teachingTarget" label="教学对象：" prop="teachingTarget">
            <el-col :span="12">
              <el-select
                v-model="ruleForm.teachingTarget.cateId"
                style="width: 100%;"
                placeholder="请输入或选择标签"
                :disabled="$route.query && $route.query.param? true : false"
                @change="getSubject(ruleForm.teachingTarget.cateId)"
              >
                <el-option
                  v-for="item in options.teachingTarget"
                  :key="item.cateId"
                  :label="item.itemName"
                  :value="item.cateId"
                />
              </el-select>
            </el-col>
          </el-form-item>

          <el-form-item label="学段-学科：">
            <!-- prop="subject" -->
            <el-col
              v-if="ruleForm.teachingTarget && options.phase && options.phase.categoryVoList"
              :span="6"
            >
              <el-select
                v-model="ruleForm.phase.cateId"
                :disabled="$route.query && $route.query.param? true : false"
                style="width: 100%;"
                placeholder="请输入或选择标签"
                @change="handleItemChange(ruleForm.phase.cateId)"
              >
                <el-option
                  v-for="item in options.phase.categoryVoList"
                  :key="item.cateId"
                  :label="item.itemName"
                  :value="item.cateId"
                />
              </el-select>
            </el-col>
            <el-col v-else :span="6">
              <el-select v-model="ruleForm.phase" disabled placeholder="请选择">
                <el-option
                  v-for="item in options.phase.categoryVoList"
                  :key="item.cateId"
                  :label="item.itemName"
                  :value="item.cateId"
                />
              </el-select>
            </el-col>

            <el-col
              v-if="
                ruleForm.phase &&
                  options.subject &&
                  options.subject.categoryVoList
              "
              :span="6"
            >
              <el-select
                v-model="ruleForm.subject.cateId"
                style="width: 100%;"
                placeholder="请输入或选择标签"
                :disabled="$route.query && $route.query.param? true : false"
              >
                <el-option
                  v-for="item in options.subject.categoryVoList"
                  :key="item.cateId"
                  :label="item.itemName"
                  :value="item.cateId"
                />
              </el-select>
            </el-col>
            <el-col v-else :span="6">
              <el-select v-model="ruleForm.subject" disabled placeholder="请输入或选择标签">
                <el-option
                  v-for="item in options.subject.categoryVoList"
                  :key="item.cateId"
                  :label="item.itemName"
                  :value="item.cateId"
                />
              </el-select>
            </el-col>
          </el-form-item>

          <!-- 栏目分类 -->
          <el-form-item v-if="options.cateTagsList" label="分类：">
            <el-col :span="12">
              <el-cascader
                v-model="ruleForm.cateTagsSelect"
                style="width: 100%;"
                :options="options.cateTagsList"
                :props="{
                  multiple: true,
                  value: 'tagsId',
                  label: 'tagsName',
                  children: 'sub',
                  checkStrictly: true
                }"
                clearable
                filterable
                @keyup.enter.native="tabsKeyup($event, 1)"
              />
            </el-col>
          </el-form-item>

          <el-form-item v-if="options.colTagsList" label="标签：">
            <el-col :span="12">
              <el-cascader
                v-model="ruleForm.colTagsSelect"
                style="width: 100%;"
                :options="options.colTagsList"
                :props="{
                  multiple: true,
                  value: 'tagsId',
                  label: 'tagsName',
                  children: 'sub',
                  checkStrictly: true
                }"
                filterable
                clearable
                @keyup.enter.native="tabsKeyup($event, 2)"
              />
            </el-col>
          </el-form-item>
        </el-form>
      </div>

      <div class="teaching-box">
        <div class="title">
          <div class>
            <el-row>
              <el-col :span="12">允许报名</el-col>
              <el-col :span="4">
                <el-switch v-model="allowSignup" active-color="#13ce66" inactive-color="#ff4949" />
              </el-col>
            </el-row>
          </div>
        </div>

        <el-form ref="ruleForm" class="teaching-form" label-width="140px" :model="ruleForm">
          <!-- v-if="options.teachingTarget" -->
          <el-form-item label="报名人数：" prop="quota">
            <el-col :span="12">
              <el-input
                v-model.number="ruleForm.quota"
                :disabled="!allowSignup"
                placeholder="设置报名人数(不填代表不限制)"
              />
            </el-col>
          </el-form-item>

          <el-form-item label="参加人员级别：">
            <!-- prop="subject" -->
            <el-col :span="12">
              <el-select
                v-model="ruleForm.levelLimit"
                :disabled="!allowSignup"
                style="width: 100%;"
                placeholder="参加人员级别"
              >
                <el-option
                  v-for="item in options.userTitleList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-col>
          </el-form-item>

          <!-- <el-form-item label="邀请老师：">
            <el-col :span="12">
              <el-select
                v-model="ruleForm.teachingTarget"
                :disabled="!ruleForm.allowSignup"
                style="width: 100%;"
                placeholder="邀请老师参加"
                @change="getSubject"
              >
                <el-option
                  v-for="item in options.teachingTarget"
                  :key="item.cateId"
                  :label="item.itemName"
                  :value="item.cateId"
                />
              </el-select>
            </el-col>
          </el-form-item>-->
        </el-form>
      </div>

      <div class="teaching-box">
        <div class="title">
          <div class>
            <el-row>
              <el-col :span="12">允许文件上传</el-col>
              <el-col :span="4">
                <el-switch v-model="allowUpload" active-color="#13ce66" inactive-color="#ff4949" />
              </el-col>
            </el-row>
          </div>
        </div>

        <el-form ref="file-form" class="teaching-form" label-width="140px" :model="ruleForm">
          <el-form-item>
            <el-col :span="12">
              <el-upload
                class="upload-demo"
                :action="action"
                :header="uploadHeader"
                :data="uploadForm"
                :show-file-list="true"
                :on-success="uploadSuccess"
                :before-upload="beforeUpload"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :file-list="ruleForm.files"
                :disabled="!allowUpload"
              >
                <el-button size="small" icon="el-icon-upload2" :disabled="!allowUpload">上传文件</el-button>
                <div slot="tip" class="el-upload__tip">支持扩展名：.ppt .xls .doc .docx .pdf .jpg...</div>
              </el-upload>
            </el-col>
          </el-form-item>
        </el-form>
      </div>

      <div class="button-box">
        <button class="default" @click="next('first')">取消</button>
        <button class="submit" @click="onSubmit('ruleForm')">立即发布</button>
      </div>
    </div>
  </div>
</template>

<script>
import { preUpload } from '@/api/uploads';
import {
  getLiveDetail,
  findColumnTags,
  findByPCateId,
  findTagsList,
  updateTeaching
} from '@/api/activity';
import { userTitleList } from './data.js';
import { reduceArr, assignment, compose, getTagsItems, getParents } from '@/utils/categoryOrTags';
import { getTimes } from '@/utils/time';
export default {
  name: 'Second',
  props: ['list'],
  data () {
    var checkQuota = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('报名人数不能为空'));
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error('请输入数字值'));
        } else {
          callback();
        }
      }, 1000);
    };
    return {
      values: true,
      action: 'https://yes910-pub.obs.cn-south-1.myhuaweicloud.com',
      uploadHeader: {
        'Content-Type': 'multipart/form-data'
      },
      uploadForm: {},

      disabled: false,
      value: true,
      options: {
        teachingTarget: '', // 教学成长
        phase: '', // 学段
        subject: '', // 学科
        cateTagsList: '',
        colTagsList: '',
        userTitleList: userTitleList // 职称
      },
      ruleForm: null,
      allowSignup: this.list.allowSignup,
      allowUpload: this.list.allowUpload,
      rules: {
        title: [{ required: true, message: '请输入标题!', trigger: 'blur' }],
        region: [
          { required: true, message: '请选择教研活动!', trigger: 'change' }
        ],
        coverImg: [
          { required: true, message: '请上传封面图片!', trigger: 'change' }
        ],
        teachingTarget: [
          {
            required: true,
            message: '请至少选择一个教学成长',
            trigger: 'change'
          }
        ],
        subject: [
          {
            required: true,
            message: '请至少选择一个学段-学科!',
            trigger: 'change'
          }
        ],
        cateTags: [
          {
            type: 'array',
            required: true,
            message: '请至少选择一个分类',
            trigger: 'change'
          }
        ],
        tagList: [
          {
            required: true,
            message: '请至少选择一个标签',
            trigger: 'change'
          }
        ],
        quota: [{ validator: checkQuota, trigger: 'blur' }],
        atvDescribe: [
          { required: true, message: '请输入标题!', trigger: 'blur' }
        ]
      }
    };
  },

  created () {
    this.list.teachingTarget = this.list.teachingTarget && this.list.teachingTarget.itemCode ? this.list.teachingTarget : {
      cateId: null,
      groupEnum: null,
      itemCode: null,
      itemName: null
    };
    this.list.phase = this.list.phase && this.list.phase.itemCode ? this.list.phase : {
      cateId: null,
      groupEnum: null,
      itemCode: null,
      itemName: null
    };
    this.list.subject = this.list.subject && this.list.subject.itemCode ? this.list.subject : {
      cateId: null,
      groupEnum: null,
      itemCode: null,
      itemName: null
    };

    this.ruleForm = this.list;
    if (!this.$route.query.param) {
      this.$router.push({
        path: '/activity/list',
        params: {
          tabsName: 'TeachingResearch'
        }
      });
      return;
    } else {
      // 获取教学对象 - 选项
      this.getTeachingTarget();
    }
  },
  methods: {
    // 获取教学成长-选项
    getTeachingTarget () {
      findByPCateId({
        bizTypeEnum: 'TEACHINGRESEARCH_REPORT'
      }).then(res => {
        this.options.teachingTarget = res.data.categoryVoList;

        console.log('this.options.teachingTarget:', this.options.teachingTarget);

        this.getSubject(this.ruleForm.teachingTarget.cateId);

        this.ruleForm.phase = {
          cateId: null,
          groupEnum: null,
          itemCode: null,
          itemName: null
        };
        this.ruleForm.subject = {
          cateId: null,
          groupEnum: null,
          itemCode: null,
          itemName: null
        };
      });
    },

    // 点击教学成长 获取学段-选项
    getSubject (pCateId) {
      findByPCateId({
        bizTypeEnum: 'TEACHINGRESEARCH_REPORT',
        pCateId: pCateId
      }).then(res => {
        // console.log('学段', res.data);
        this.options.phase = res.data;
        this.ruleForm.subject = {
          cateId: null,
          groupEnum: null,
          itemCode: null,
          itemName: null
        };

        this.handleItemChange(this.ruleForm.phase.cateId);
      });
    },
    // 点击学段  获取 学科-选项
    handleItemChange (val) {
      findByPCateId({
        bizTypeEnum: 'TEACHINGRESEARCH_REPORT',
        pCateId: val
      }).then(res => {
        console.log('this.options.phase:', this.options.phase);

        this.options.subject = res.data;
        this.getSelection();
      });
    },

    // 获取选项
    async getSelection () {
      // 查找栏目分类选项
      if (this.ruleForm.teachingTarget.cateId) {
        this.options.teachingTarget.map(item => {
          if (item.cateId === this.ruleForm.teachingTarget.cateId) {
            this.ruleForm.teachingTarget = item;
          }
        });
      }
      if (this.ruleForm.phase.cateId) {
        this.options.phase.map(item => {
          if (item.cateId === this.ruleForm.phase.cateId) {
            this.ruleForm.phase = item;
          }
        });
      }
      if (this.ruleForm.subject.cateId) {
        this.options.subject.map(item => {
          if (item.cateId === this.ruleForm.subject.cateId) {
            this.ruleForm.subject = item;
          }
        });
      }

      var teachingCode = this.ruleForm.teachingTarget.itemCode;
      var phaseCode = this.ruleForm.phase.itemCode;
      var subjectCode = this.ruleForm.subject.itemCode;
      var columnObj = {
        growthClassify: teachingCode || null,
        stageList: phaseCode ? [phaseCode] : null,
        subjectList: subjectCode ? [subjectCode] : null
      };
      await findColumnTags(columnObj).then(res => {
        this.options.cateTagsList = res.data;
        var cateTagsSelect = [];

        if (this.ruleForm.cateTags && this.ruleForm.cateTags.length > 0) {
          this.ruleForm.cateTags.map(item => {
            if (getParents(this.options.cateTagsList, item.tagsId, 'tagsId')) {
              cateTagsSelect.push(getParents(this.options.cateTagsList, item.tagsId, 'tagsId').reverse());
            }
          });
        }
        this.ruleForm.cateTagsSelect = cateTagsSelect;
      });

      var tagsObj = {
        groupId: null,
        growthClassify: teachingCode || null,
        stageId: phaseCode || null,
        subjectId: subjectCode || null,
        tagsKindEnum: 'TEACHINGRESEARCH',
        tagsTypeEnum: 'CATEGORY_TAGS'
      };
      // 查询标签选项
      await findTagsList(tagsObj).then(res => {
        this.options.colTagsList = res.data;
        var colTagsSelect = [];
        if (this.ruleForm.colTags && this.ruleForm.colTags.length > 0) {
          this.ruleForm.colTags.map(item => {
            if (getParents(this.options.cateTagsList, item.tagsId, 'tagsId') !== undefined) {
              colTagsSelect.push(getParents(this.options.cateTagsList, item.tagsId, 'tagsId').reverse());
            }
          });
        }

        this.ruleForm.colTagsSelect = colTagsSelect;
      });
    },

    async init () { },
    handleRemove (file, fileList) {
      console.log(file, fileList);
    },
    handlePreview (file) {
      console.log(file);
    },

    beforeRemove (file, fileList) {
      return this.$confirm(`确定移除 ${file.fileName}？`);
    },

    uploadSuccess (res, file) {
      console.log('上传成功:', URL.createObjectURL(file.raw));
      this.ruleForm.files.push({
        name: file.name,
        url: this.ruleForm.filesUrl
      });
      console.log(this.ruleForm.files);
      // this.form.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeUpload (file) {
      // const imgStr = /\.(jpg|jpeg|png|JPG|PNG|JPEG)$/;
      // if (!imgStr.test(file.name)) {
      //   this.$message.error('上传格式不对，请重新上传!');
      //   return false;
      // }
      let continueUpload = false;
      return new Promise((resolve, reject) => {
        preUpload({
          biz: 'OPEN',
          name: file.name,
          size: file.size
        })
          .then(res => {
            console.log('文件上传：', res.data);
            this.action = res.data.action;
            this.uploadForm = res.data.parameters;
            this.ruleForm.filesUrl = res.data.uri;
            continueUpload = true;
            resolve(continueUpload);
          })
          .catch(err => {
            reject(continueUpload);
          });
      });
    },

    onSubmit (formName) {
      console.log(this.ruleForm);
      this.$refs[formName].validate(valid => {
        if (valid) {
          console.log('submit!');

          for (var i in this.ruleForm) {
            if (!this.ruleForm[i]) {
              this.ruleForm[i] = '';
            }
          }

          var teachingTarget, phase, subject;

          if (this.ruleForm.teachingTarget) {
            teachingTarget = this.options.teachingTarget.filter(
              item => item.cateId === this.ruleForm.teachingTarget.cateId
            );
          }

          if (this.ruleForm.phase) {
            phase = this.options.phase.categoryVoList.filter(
              item => item.cateId === this.ruleForm.phase.cateId
            );
          }

          if (this.ruleForm.subject) {
            subject = this.options.subject.categoryVoList.filter(
              item => item.cateId === this.ruleForm.subject.cateId
            );
          }

          // 分类
          var cateTags = [];
          if (this.ruleForm.cateTagsSelect.length > 0) {
            var cateTagsSelect = getTagsItems(this.ruleForm.cateTagsSelect, this.options.cateTagsList);

            cateTagsSelect.map(item => {
              cateTags.push({
                tagsId: item.tagsId,
                tagsName: item.tagsName
              });
            });
          }

          // 标签
          var colTags = [];
          if (this.ruleForm.colTagsSelect.length > 0) {
            var colTagsSelect = getTagsItems(this.ruleForm.colTagsSelect, this.options.colTagsList);

            colTagsSelect.map(item => {
              colTags.push({
                tagsId: item.tagsId,
                tagsName: item.tagsName
              });
            });
          }

          // 文件
          var files = [];
          this.ruleForm.files.map(item => {
            files.push({
              fileId: item.fileId ? item.fileId : '',
              name: item.name,
              url: item.url
            });
          });

          var data = {
            activityId: this.$route.query.param,
            allowSignup: this.allowSignup,
            allowUpload: this.allowUpload,
            cateTags: cateTags,
            colTags: colTags,
            coverImageUrl: this.ruleForm.coverImageUrl,
            endTime: this.ruleForm.endTime,
            files: files,
            intro: this.ruleForm.intro,
            levelLimit: this.ruleForm.levelLimit,
            phase: this.ruleForm.phase,
            quota: this.ruleForm.quota,
            startTime: this.ruleForm.startTime,
            subject: this.ruleForm.subject,
            teachingTarget: this.ruleForm.teachingTarget,
            title: this.ruleForm.title
          };

          updateTeaching(data).then(res => {
            console.log(res.data);
            this.$message({
              message: '修改成功',
              type: 'success'
            });

            this.$router.push({
              path: '/activity/list',
              params: {
                tabsName: 'TeachingResearch'
              }
            });
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
      //       var birthday = new Date("July 21, 1983 01:15:00")
      // document.write(birthday.getDate())
    },

    // 下一步
    next (step) {
      this.ruleForm.step = step;
      console.log(this.ruleForm);
      // this.$emit('Callback', this.ruleForm);
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
.second {
  .avatar-uploader {
    width: 480px;
    height: 270px;
    background: rgba(0, 0, 0, 0.02) !important;
    border-radius: 16px;
    border: 1px dashed rgba(0, 0, 0, 0.15);
    border-radius: 8px;
    overflow: hidden;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    margin: 0 auto;
    height: 100%;
    display: block;
  }

  .step {
    span {
      margin: 0 8px;
    }
    .el-input {
      width: 90% !important;
    }
    .step-btn {
      margin-left: 20px;
      margin-top: 10px;
    }
  }

  .crumbs-box {
    background-color: white;
    height: 46px;
    padding-left: 40px;
    .el-breadcrumb {
      line-height: 40px;
    }
  }
  .content-box {
    padding: 0 40px;
    padding-bottom: 0;
    overflow: hidden;
    background: rgba(245, 246, 250, 1);
    .teaching-title {
      font-size: 20px;
      font-family: MicrosoftYaHei;
      color: rgba(0, 0, 0, 0.85);
      line-height: 28px;
    }

    .teaching-box {
      background-color: white;
      margin-top: 24px;
      padding-bottom: 16px;
      border-radius: 16px;
      .title {
        border-bottom: 1px solid #d9d9d9;
        line-height: 46px;
        padding: 0 40px;
        font-size: 16px;
        font-family: MicrosoftYaHei;
        color: rgba(0, 0, 0, 0.85);
      }

      .teaching-form {
        padding: 40px;

        .uploader-icon {
          margin-top: 96px;
          line-height: 40px;
          height: 40px;
          margin-bottom: 6px;
        }

        .upload__text {
          font-family: MicrosoftYaHei;
          color: rgba(0, 0, 0, 0.45);
          line-height: 24px;
          margin-bottom: 4px;
        }
      }

      .upload-demo {
        // border: 1px solid red;

        // width: 480px;
        // height: 270px;
        // background: rgba(0, 0, 0, 0.02);
        // border-radius: 16px;
        // border: 1px solid rgba(0, 0, 0, 0.15);
      }
      .textarea {
        height: 300px;
        padding: 20px;
        background: rgba(0, 0, 0, 0.02);
        border-radius: 4px;
        border: 1px solid rgba(0, 0, 0, 0.15);
      }
    }

    .button-box {
      padding: 40px;
      background-color: #f5f6fa;
      .default {
        width: 94px;
        height: 40px;
        background: rgba(255, 255, 255, 1);
        border-radius: 4px;
        border: 1px solid rgba(0, 0, 0, 0.15);
        margin-right: 30px;
        cursor: pointer;
      }
      .submit {
        width: 128px;
        height: 40px;
        border: none;
        background: rgba(84, 184, 123, 1);
        border-radius: 4px;

        font-size: 16px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: rgba(255, 255, 255, 1);
        line-height: 24px;
        cursor: pointer;
      }
    }
  }
}
</style>
